package com.example.cloudmusic.home

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.cloudmusic.MainViewModel
import com.example.cloudmusic.databinding.FragmentHomeBinding
import com.example.cloudmusic.home.adapter.HomeAdapter
import com.example.cloudmusic.home.model.*
import com.example.cloudmusic.home.repository.DataSourceType
import com.example.cloudmusic.utils.ConversionTool
import com.example.cm_base.BaseFragment
import com.google.android.material.snackbar.Snackbar
import java.util.Calendar

class HomeFragment : BaseFragment<FragmentHomeBinding, HomeViewModel,MainViewModel>() {

    private lateinit var homeAdapter: HomeAdapter
    private var errorSnackbar: Snackbar? = null

    override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) {
        initView()
        loadData()
    }

    private fun initView() {
        updateGreeting()

        homeAdapter = HomeAdapter()
        binding.cmRecycelrView.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = homeAdapter
        }

        binding.cmHomeRoot.setOnRefreshListener {
            viewModel.refreshData()
        }

        binding.cmTvGreeting.setOnClickListener {
            viewModel.toggleDataSource()
        }

        setupClickListeners()
    }
    
    private fun updateGreeting() {
        val calendar = Calendar.getInstance()
        val hourOfDay = calendar.get(Calendar.HOUR_OF_DAY)
        
        val greeting = when {
            hourOfDay < 6 -> "凌晨好"
            hourOfDay < 12 -> "上午好"
            hourOfDay < 14 -> "中午好"
            hourOfDay < 18 -> "下午好"
            else -> "晚上好"
        }
        
        val dataSourceInfo = when (viewModel.dataSourceType.value) {
            DataSourceType.MOCK -> "[模拟数据]"
            DataSourceType.NETWORK -> "[网络数据]"
            else -> ""
        }
        
        binding.cmTvGreeting.text = "$greeting $dataSourceInfo"
    }

    private fun setupClickListeners() {
        homeAdapter.listener = object : HomeAdapter.OnItemClickListener {
            override fun onMusicStyleItemClick(position: Int, item: MusicStyle) {
                showToast("点击了音乐风格：${item.style}")
            }
            
            override fun onRecommendedPlaylistsClick(position: Int, item: Playlist) {
                showToast("点击了推荐歌单：${item.title}")
            }
            
            override fun onPersonalPlaylistClick(position: Int, item: Playlist) {
                showToast("点击了个人歌单：${item.title}")
            }

            override fun onBannerClick(position: Int, item: Banner) {
                showToast("点击了轮播图：${position + 1}")
            }

            override fun onArtistClick(position: Int, item: Artist) {
                showToast("点击了艺人：${item.name}")
            }

            override fun onMusicClick(position: Int, item: Music) {
                showToast("点击了歌曲：${item.title} - ${item.artist}")
                if (item.playUrl.isNotEmpty()) {
                    try {
                        shareViewModel.playSong(ConversionTool.musicToSongInfo(item))
                    } catch (e: Exception) {
                        showToast("播放失败：${e.message}")
                    }
                } else {
                    showToast("无法播放：歌曲链接为空")
                }
            }
        }
    }

    override fun initObservers() {
        viewModel.sections.observe(viewLifecycleOwner) { sections ->
            homeAdapter.setData(sections)
            errorSnackbar?.dismiss()
        }

        viewModel.isLoading.observe(viewLifecycleOwner) { isLoading ->
            binding.cmHomeRoot.isRefreshing = isLoading
        }

        viewModel.errorMessage.observe(viewLifecycleOwner) { errorMsg ->
            if (errorMsg.isNotEmpty()) {
                showErrorMessage(errorMsg)
            }
        }

        viewModel.dataSourceType.observe(viewLifecycleOwner) { dataSourceType ->
            updateGreeting()
            val message = when (dataSourceType) {
                DataSourceType.MOCK -> "已切换到模拟数据"
                DataSourceType.NETWORK -> "已切换到网络数据"
                else -> ""
            }
            if (message.isNotEmpty()) {
                showToast(message)
            }
        }
    }

    private fun loadData() {
        viewModel.loadHomeData()
    }
    
    private fun showErrorMessage(message: String) {
        errorSnackbar?.dismiss()
        errorSnackbar = Snackbar.make(binding.root, message, Snackbar.LENGTH_INDEFINITE)
            .setAction("重试") {
                viewModel.retryLoadData()
            }
            .setActionTextColor(resources.getColor(android.R.color.holo_red_light))
        
        errorSnackbar?.show()
        Thread{
            Thread.sleep(2000)
            errorSnackbar?.dismiss()
        }.start()
    }

    private fun showToast(message: String) {
        Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
    }

    override fun sharedViewModel(): Boolean = true
    
    override fun onDestroyView() {
        errorSnackbar?.dismiss()
        errorSnackbar = null
        super.onDestroyView()
    }
}